package com.xz.stu.server.controller;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import com.xz.stu.server.vo.student.*;
import com.xz.stu.server.service.StudentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - 学生管理")
@RestController
@RequestMapping("admin-api/school/student")
@Validated
public class StudentController {

    @Resource
    private StudentService studentService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping("/create")
    @Operation(summary = "创建学生")
    public CommonResult<Long> createStudent(@Valid @RequestBody StudentCreateReqVO createReqVO) {
        return success(studentService.createStudent(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新学生")
    public CommonResult<Boolean> updateStudent(@Valid @RequestBody StudentUpdateReqVO updateReqVO) {
        studentService.updateStudent(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除学生")
    public CommonResult<Boolean> deleteStudent(@PathVariable("id") List<Long> id) {
        studentService.deleteStudent(id);
        return success(true);
    }

    @GetMapping("/get/{id}")
    @Operation(summary = "获得学生")
    public CommonResult<StudentRespVO> getStudent(@PathVariable("id") Long id) {
        return success(studentService.getStudent(id));
    }

    @GetMapping("/list")
    @Operation(summary = "获得学生列表")
    public CommonResult<List<StudentRespVO>> getStudentList(@Valid StudentListReqVO listReqVO) {
        return success(studentService.getStudentList(listReqVO));
    }

    @GetMapping("/page")
    @Operation(summary = "获得学生列表-分页")
    public CommonResult<PageResult<StudentRespVO>> getStudentListPage(@Valid StudentListPageReqVO listReqVO) {
        return success(studentService.getStudentListPage(listReqVO));
    }
    // 导出学生信息为 Excel 文件
    @GetMapping("/export")
    public void exportStudents(HttpServletResponse response,@Valid StudentListPageReqVO listReqVO) throws IOException {
        PageResult<StudentRespVO> studentListPage = studentService.getStudentListPage(listReqVO);
        List<StudentExcelVO> studentList = BeanUtils.toBean(studentListPage.getList(), StudentExcelVO.class);
        AtomicInteger i= new AtomicInteger();
        studentList.forEach(student -> {
            student.setGenderC(student.getGender()==0 ? "男" : "女");
            student.setNo((long) i.incrementAndGet());
        });
        ExcelUtils.write(response, "学生信息.xlsx", "学生信息", StudentExcelVO.class, studentList);
    }
    // 导入模版
    @GetMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        StudentTemplateVO studentTemplateVO = new StudentTemplateVO();
        studentTemplateVO.setStudentId("202101094119(示例数据请删除)");
        studentTemplateVO.setName("张三(示例数据请删除)");
        studentTemplateVO.setGenderC("男(示例数据请删除)");
        studentTemplateVO.setBirthDate("1990-01-01(示例数据请删除)");
        studentTemplateVO.setEnrollDate("2020-09-01(示例数据请删除)");
        studentTemplateVO.setPhone("13800000000(示例数据请删除)");
        studentTemplateVO.setDeptName("计算机科学与技术(示例数据请删除)");
        studentTemplateVO.setClassName("计算机科学与技术1班(示例数据请删除)");
        ExcelUtils.write(response, "学生信息.xlsx(示例数据请删除)", "学生信息", StudentTemplateVO.class, Collections.singletonList(studentTemplateVO));
    }

    // 导入学生信息从 Excel 文件
    @PostMapping("/import")
    public CommonResult<Map<String,String>> importStudents(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            HashMap<String, String> map = new HashMap<>();
            map.put("code", "300");
            map.put("msg", "文件为空，请选择有效的 Excel 文件。");
            return success(map);
        }
        List<StudentTemplateVO> students = ExcelUtils.read(file, StudentTemplateVO.class);
         return studentService.importStudents(students);
    }

    //导出异常信息
    @GetMapping("/exportAbnormal")
    public void exportAbnormal(HttpServletResponse response) throws IOException {
        Long id = Objects.requireNonNull(SecurityFrameworkUtils.getLoginUser()).getId();
        //构架key
        String key = "student:import:abnormal:" + id;
        String s = redisTemplate.opsForValue().get(key);
        //删除redis缓存信息
        Boolean delete = redisTemplate.delete(key);
        List<StudentTemplateAbnormalVO> studentList = JsonUtils.parseArray(s, StudentTemplateAbnormalVO.class);

        ExcelUtils.write(response, "学生信息.xlsx", "学生信息", StudentTemplateAbnormalVO.class, studentList);
    }
}
